import re

from django.conf import settings
from django.contrib.auth.backends import ModelBackend
from apps.users.models import User
from meiduo_mall.settings.dev import logger
from utils.seceret import SecretOauth


def generate_verify_email_url(user):
    data_dict = {'user_id':user.id,'email':user.email}
    secret_data = SecretOauth().dumps(data_dict)

    verify_url = settings.EMAIL_ACTIVE_URL + '?TOKEN' + secret_data

    return verify_url


def get_user_by_account(account):
    try:
        if re.match('^1[345789]\d{9}$', account):
            user = User.objects.get(mobile=account)

        else:
            user = User.objects.get(username=account)
    except Exception as e:
        logger.error(e)
        return None
    else:
        return user

class UsernameMbileAuthBackend(ModelBackend):

    def authenticate(self, request, username=None, password=None, **kwargs):
        user = get_user_by_account(username)

        if user and user.check_password(raw_password=password):
            return user

